<?php

namespace App\Admin\Controllers\User;

use App\Admin\Extensions\Column\OpenMap;
use App\Admin\Extensions\Column\OpenNote;
use App\Models\User\Account;
use App\Models\User\AccountDetail;
use App\Models\User\User;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Widgets;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AccountController extends Controller
{
    use ModelForm;

    public $header = '经验值及校币';

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Account::class, function (Grid $grid) {

            $grid->model()->orderBy('user_id','desc');

            $grid->user()->id('用户id');
            $grid->user()->telephone('手机号');
            $grid->user()->username('用户昵称');
            $grid->user()->initial_role_id('身份')->using([
                '1'=>'老师',
                '2'=>'家长',
            ]);
            $grid->money('当前校币');
            $grid->expe('经验值');
            $grid->column('操作')->openNote(function () {

            }, '修改数值');

            $grid->disableCreateButton();
            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();

                $actions->append('<a href="'.$actions->getResource().'/money/'.$actions->row->user_id.'"><i class="fa fa-eye"></i>校币明细</a>');
                $actions->append('&nbsp;&nbsp;<a href="'.$actions->getResource().'/expe/'.$actions->row->user_id.'"><i class="fa fa-eye"></i>经验明细</a>');
            });

            $grid->filter(function (Grid\Filter $filter){
                $filter->disableIdFilter();
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('user', function ($query) use ($input) {
                        $query->where('telephone','like', "%$input%");
                    });

                }, '手机号', 'telephone');

                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('user', function ($query) use ($input) {
                        $query->where('username','like', "%$input%");
                    });

                }, '用户昵称', 'username');
            });


            /*$grid->model()->getUser();

            $grid->user_id('用户id');
            $grid->telephone('手机号');
            $grid->username('用户昵称');
            $grid->initial_role_id('身份')->using([
                '1'=>'老师',
                '2'=>'家长',
            ]);
            $grid->money('当前校币');
            $grid->expe('经验值');

            $grid->disableCreateButton();
            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();

                $actions->append('<a href="'.$actions->getResource().'/money/'.$actions->row->user_id.'"><i class="fa fa-eye"></i>校币明细</a>');
                $actions->append('&nbsp;&nbsp;<a href="'.$actions->getResource().'/expe/'.$actions->row->user_id.'"><i class="fa fa-eye"></i>经验明细</a>');
            });

            $grid->column('操作')->openNote(function () {

            }, '修改数值');*/

        });
    }

    protected function form()
    {
        return Admin::form(Account::class, function (Form $form) {

            $form->text('gold', '可用校币')->rules('required|integer');
            $form->text('expe', '经验值')->rules('required|regex:/^[0-9]+([.]{1}[0-9]{1})?$/',[
                'regex' => '经验值 必须是个整数或者1位小数的数字'
            ]);
            $form->disableViewCheck();
            $form->disableEditingCheck();
            $form->tools(function (Form\Tools $tools){
               $tools->disableDelete();
               $tools->disableView();
            });
        });
    }

    public function money($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('校币明细');
            $content->description('description');

            $user = User::findOrFail($id);

            $user_vip = $user->vip()->get()->toArray();

            $user_account = $user->account()->get()->toArray();

            if ($user_vip){
                $user_vip = pos($user_vip);
            }

            $user_account = pos($user_account);

            $headers = ['用户Id', '用户昵称', '手机号', '会员等级', '会员身份', '当前校币','经验值'];
            $rows = [
                [
                    $user['id'],
                    $user['username'],
                    $user['telephone'],
                    @$user_vip['name'],
                    $user['initial_role_id'] == 1 ? '老师' : '家长',
                    $user_account['money'],
                    $user_account['expe']
                ],
            ];
            $table = new Widgets\Table($headers, $rows);
            $box1 = new Widgets\Box($user['username'], $table);
            $content->row($box1->solid()->style('primary'));

            $grid = Admin::grid(AccountDetail::class, function (Grid $grid) use ($id) {

                $grid->model()->where([
                    ['user_id',$id],
                    ['money','!=',null],
                    ['money','!=','']
                ])->orderBy('id','desc');
                $grid->id('id');
                $grid->money('校币来源');
                $grid->detail('校币变化')->display(function ($v){

                    list($expe,$money,$gold) = explode('-',$v);
                    if ($this->name == 'ADMIN_REDUCE'){
                        return '- ' . $money;
                    }else{
                        return '+ ' . $money;
                    }
                });
                $grid->sdate('时间');
                $grid->note('备注');

                $grid->disableCreateButton();
                $grid->disableActions();

                $grid->disableRowSelector();

                //搜索栏
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->like('money','校币来源');
                    //$filter->between('sdate', '创建时间')->timestamp();
                    /*$filter->where(function ($query) {
                        $input = $this->input;
                        $query->whereHas('tags', function ($query) use ($input) {
                            $query->where('name', $input);
                        });
                    }, 'Has tag', 'tag');*/
                });
            });

            $box2 = new Widgets\Box('校币明细', $grid->render());
            $content->row($box2->solid()->style('primary'));

        });
    }

    public function expe($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('经验明细');
            $content->description('description');

            $user = User::find($id);
            $user_vip = $user->vip()->get()->toArray();
            $user_account = $user->account()->get()->toArray();

            if ($user_vip){
                $user_vip = pos($user_vip);
            }

            $user_account = pos($user_account);

            $headers = ['用户Id', '用户昵称', '手机号', '会员等级', '会员身份', '当前校币','经验值'];
            $rows = [
                [
                    $user['id'],
                    $user['username'],
                    $user['telephone'],
                    @$user_vip['name'],
                    $user['initial_role_id'] == 1 ? '老师' : '家长',
                    $user_account['money'],
                    $user_account['expe']
                ],
            ];
            $table = new Widgets\Table($headers, $rows);
            $box1 = new Widgets\Box($user['username'], $table);
            $content->row($box1->solid()->style('primary'));

            $grid = Admin::grid(AccountDetail::class, function (Grid $grid) use ($id) {

                $grid->model()->where([
                    ['user_id',$id],
                    ['expe','!=',null],
                    ['expe','!=','']
                ])->orderBy('id','desc');

                $grid->expe('经验值来源');
                $grid->detail('经验值变化')->display(function ($v){

                    list($expe,$money,$gold) = explode('-',$v);
                    if ($this->name == 'ADMIN_REDUCE'){
                        return '- ' . $expe;
                    }else{
                        return '+ ' . $expe;
                    }
                });
                $grid->sdate('时间');
                $grid->note('备注');

                $grid->disableCreateButton();
                $grid->disableActions();
                $grid->disableRowSelector();

                //搜索栏
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->like('expe','经验值来源');
                });
            });

            $box2 = new Widgets\Box('经验值明细', $grid->render());
            $content->row($box2->solid()->style('primary'));

        });
        
    }

    public function updateAccount(Request $request)
    {
        $user_id = $request->input('user_id');
        $radio_money = $request->input('radio_money');
        $radio_expe = $request->input('radio_expe');
        $money = $request->input('money',0);
        $expe = $request->input('expe',0);
        $note = $request->input('note');

        $status = true;

        if (!$money && !$expe){
            return response()->json([
                'status'  => false,
                'message' => '校币和经验值不能同时为空',
            ]);
        }

        $user = User::find($user_id);

        //用户是否存在
        if ($user){

            $account = Account::where('user_id',$user_id)->first();
            $accountDetail = new AccountDetail();

            //经验值
            if ($expe){
                //$radio_expe =1 增加 =0 减少
                if ($radio_expe){
                    $name = 'ADMIN_ADD';

                    $account->increment('expe',$expe);

                } else {
                    $name = 'ADMIN_REDUCE';

                    $account->decrement('expe',$expe);
                }

                $accountDetail->user_id = $user_id;
                $accountDetail->expe    = '管理员修改';
                $accountDetail->detail  = "$expe-0-0";
                $accountDetail->name    = $name;
                $accountDetail->sdate   = time();
                $accountDetail->note    = $note;

                $status = $accountDetail->save();
            }


            //校币
            if ($money){
                //$radio_gold =1 增加 =0 减少
                if ($radio_money){
                    //add
                    $name = 'ADMIN_ADD';

                    $account->increment('money',$money);

                } else {
                    //reduce
                    $name = 'ADMIN_REDUCE';

                    $account->decrement('money',$money);
                }

                $accountDetail->user_id = $user_id;
                $accountDetail->money   = '管理员修改';
                $accountDetail->detail  = "0-$money-0";
                $accountDetail->name    = $name;
                $accountDetail->sdate   = time();
                $accountDetail->note    = $note;

                $status = $accountDetail->save();
            }

        }else{
            $status = false;
            $msg = '用户不存在';
        }


        return response()->json([
            'status'  => $status,
            'message' => $msg ?? '修改成功',
        ]);

    }


}
